<template>
  <div class="equip-wrap-common">
    <div class="flex-row">
      <px-form ref="queryRef" class="custom-form-ui" :model="queryParams" :inline="true" label-width="68px">
        <px-form-item label="组件名称" prop="componentName">
          <px-input v-model="queryParams.componentName" placeholder="请输入组件名称" clearable @keyup.enter="queryTable">
            <template #suffix>
              <px-icon style="cursor: pointer" @click="queryTable">
                <search />
              </px-icon>
            </template>
          </px-input>
        </px-form-item>
        <px-form-item label="所属菜单" prop="resourceId">
          <px-cascader
            v-model="queryParams.resourceId"
            filterable
            clearable
            style="width: 400px"
            :options="menuTreeData"
            :props="cascaderProps"
            placeholder="请选择所属菜单"
          />
        </px-form-item>
        <px-button style="margin-top: -16px" type="primary" @click="queryTable">查询</px-button>
        <px-button style="margin-top: -16px" @click="resetQuery">重置</px-button>
      </px-form>
      <px-button v-has="'SYSTEM_BASE_BOARD_MANAGE_ADD'" type="primary" icon="Plus" @click="handleAdd">新增组件</px-button>
    </div>

    <px-table :data="tableData" class="equip-table" height="calc(100vh - 268px)" border>
      <px-table-column
        v-for="(item, index) in tableColumns"
        :key="index"
        :label="item.label"
        :min-width="item.minWidth"
        :align="item.align"
        :show-overflow-tooltip="item.showOverflowTooltip"
        :fixed="item.fixed"
      >
        <template v-if="item.type === 'ratio'" #default="scope"> {{ scope.row.width }}*{{ scope.row.length }} </template>
        <template v-else-if="item.type === 'status'" #default="scope">
          <px-tag :type="scope.row.isUse === 1 ? 'warning' : 'success'">{{ scope.row.isUse === 1 ? "禁用" : "启用" }}</px-tag>
        </template>
        <template v-else #default="scope">{{
          scope.row[item.prop] === 0 ? scope.row[item.prop] : scope.row[item.prop] ? scope.row[item.prop] : "-"
        }}</template>
      </px-table-column>
      <px-table-column fixed="right" label="操作" min-width="120" align="center">
        <template #default="scope">
          <px-tooltip content="修改" placement="top">
            <px-button v-has="'SYSTEM_BASE_BOARD_MANAGE_EDIT'" link type="primary" icon="EditPen" @click="handleEdit(scope.row)" />
          </px-tooltip>
          <px-tooltip :content="scope.row.isUse === 1 ? '启用' : '禁用'" placement="top">
            <px-button
              v-has="'SYSTEM_BASE_BOARD_MANAGE_DISABLE'"
              link
              type="primary"
              :icon="scope.row.isUse === 1 ? 'Check' : 'Close'"
              @click="handleDisabled(scope.row)"
            />
          </px-tooltip>
          <px-tooltip content="删除" placement="top">
            <px-button v-has="'SYSTEM_BASE_BOARD_MANAGE_DEL'" link type="primary" icon="Delete" @click="handleDelete(scope.row)" />
          </px-tooltip>
        </template>
      </px-table-column>
    </px-table>
    <pagination
      v-show="total > 0"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      class="equip-table-pagination"
      :total="total"
      @pagination="queryTable"
    />
    <!-- 添加或修改参数配置对话框 -->
    <px-dialog
      v-model="open"
      :close-on-click-modal="false"
      :title="formValue.componentNumber ? '修改组件' : '新增组件'"
      width="900px"
      destroy-on-close
      append-to-body
      @close="cancel"
    >
      <px-form ref="boardRef" :model="formValue" :rules="rules" label-width="140px">
        <px-form-item label="组件名称" prop="componentName">
          <px-input v-model="formValue.componentName" maxlength="50" clearable placeholder="请输入组件名称" />
        </px-form-item>
        <px-form-item label="能源类型" prop="energyType">
          <px-select v-model="formValue.energyType" style="width: 100%" filterable clearable>
            <px-option v-for="item in energyTypeList" :key="item.value" :label="item.name" :value="item.value" />
          </px-select>
        </px-form-item>
        <EqpMultipleFactorySelect :isRequired="true" propValue="facCode" :facCode="formValue.facCode" @changeFactory="changeInFactory" />
        <px-form-item label="系统" prop="systemCode">
          <px-cascader
            ref="systemRef"
            v-model="formValue.systemCode"
            filterable
            clearable
            style="width: 100%"
            :options="systemList"
            :props="systemProps"
            placeholder="请选择系统"
          />
        </px-form-item>
        <px-form-item label="所属菜单" prop="resourceId">
          <px-cascader
            ref="menuRef"
            v-model="formValue.resourceId"
            filterable
            clearable
            style="width: 100%"
            :options="menuTreeData"
            :props="cascaderProps"
            placeholder="请选择所属菜单"
          />
        </px-form-item>
        <px-form-item label="组件类型" prop="componentType">
          <px-select v-model="formValue.componentType" filterable clearable style="width: 100%">
            <px-option v-for="item in chartTypeList" :key="item.id" :label="item.name" :value="item.value" />
          </px-select>
        </px-form-item>
        <px-form-item label="预设大小比例" prop="width">
          <span style="margin-right: 6px; color: #444">宽</span>
          <px-input-number v-model="formValue.width" :min="1" :max="4" />
          <span style="margin: 0 6px; color: #666">*</span>
          <span style="margin-right: 6px; color: #444">高</span>
          <px-input-number v-model="formValue.length" :min="1" :max="3" />
        </px-form-item>
        <px-form-item label="是否需要时间筛选" prop="isFilter">
          <px-radio-group v-model="formValue.isFilter">
            <px-radio :label="0">否</px-radio>
            <px-radio :label="1">是</px-radio>
          </px-radio-group>
        </px-form-item>
        <px-form-item label="接口地址" prop="urlAddress">
          <px-input v-model="formValue.urlAddress" maxlength="200" clearable placeholder="请输入接口地址" />
        </px-form-item>
      </px-form>
      <template #footer>
        <div class="dialog-footer">
          <px-button @click="cancel">取 消</px-button>
          <px-button type="primary" @click="submitForm">确 定</px-button>
        </div>
      </template>
    </px-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "SYSTEM_BASE_BOARDMANAGE"
});
import { queryDictData } from "@/api/common";
import { querySystemSelect } from "@/api/equip/archive";
import { addTableData, delTableData, disabledData, editTableData, getMenuData, getTableData } from "@/api/system/board";
import { PxMessage, PxMessageBox } from "px-ui";
import { getCurrentInstance, onMounted, reactive, ref, toRefs } from "vue";

const { proxy }: any = getCurrentInstance();

const open = ref(false);
const loading = ref(true);

const systemProps = {
  children: "children",
  label: "name",
  value: "code"
};

const cascaderProps = {
  children: "children",
  label: "title",
  value: "id"
};

const data = reactive<Record<string, any>>({
  queryParams: {
    pageNum: 1,
    pageSize: 20
  },
  formValue: {
    width: 1,
    length: 1,
    facCode: ""
  },
  rules: {
    componentName: [{ required: true, message: "组件名称不能为空", trigger: "blur" }],
    resourceId: [{ required: true, message: "所属菜单不能为空", trigger: "change" }],
    componentType: [{ required: true, message: "组件类型不能为空", trigger: "change" }],
    width: [{ required: true, message: "宽不能为空", trigger: "blur" }],
    length: [{ required: true, message: "高不能为空", trigger: "blur" }],
    isFilter: [{ required: true, message: "是否需要时间筛选不能为空", trigger: "blur" }]
  },
  energyTypeList: [],
  tableData: [],
  total: 0,
  menuTreeData: [],
  chartTypeList: [],
  systemList: [],
  tableColumns: [
    { prop: "componentName", label: "组件名称", minWidth: "160", showOverflowTooltip: true, fixed: "left" },
    { prop: "isUse", label: "组件状态", minWidth: "90", showOverflowTooltip: true, fixed: "left", type: "status" },
    { prop: "resourceDesc", label: "所属菜单", minWidth: "240", showOverflowTooltip: true },
    { prop: "energyTypeDesc", label: "能源类型", minWidth: "90", showOverflowTooltip: true },
    { prop: "systemDesc", label: "子系统", minWidth: "240", showOverflowTooltip: true },
    { prop: "componentTypeDesc", label: "组件类型", minWidth: "100", showOverflowTooltip: true },
    { prop: "ratio", label: "预设大小", minWidth: "100", type: "ratio", showOverflowTooltip: true },
    { prop: "isFilterDesc", label: "是否需要时间筛选", minWidth: "140", showOverflowTooltip: true },
    { prop: "urlAddress", label: "接口地址", minWidth: "170", showOverflowTooltip: true }
  ]
});

const { queryParams, formValue, rules, energyTypeList, tableData, total, menuTreeData, chartTypeList, systemList, tableColumns } = toRefs(data);

/** 查询自定义组件列表 */
const queryTable = async () => {
  loading.value = true;
  const { resourceId } = queryParams.value;
  const res: any = await getTableData({ ...queryParams.value, resourceId: resourceId ? resourceId[resourceId?.length - 1] : "" });
  tableData.value = res?.data;
  total.value = res?.total;
  loading.value = false;
};

const getSystem = async () => {
  systemList.value = await querySystemSelect({ className: "" });
};

const handleGetDictData = async () => {
  energyTypeList.value = await queryDictData({ typeCode: "ENERGY" });
  chartTypeList.value = await queryDictData({ typeCode: "COMPONENT_TYPE" });
  menuTreeData.value = await getMenuData();
  getSystem();
};

onMounted(async () => {
  await handleGetDictData();
  await queryTable();
});

/** 取消按钮 */
const cancel = () => {
  open.value = false;
  proxy.resetForm("boardRef");
  formValue.value = {
    width: 1,
    length: 1
  };
};

/** 重置按钮操作 */
const resetQuery = () => {
  proxy.resetForm("queryRef");
  queryParams.value.facCode = "";
  queryTable();
};

// 厂区组件调用父组件
const changeInFactory = val => {
  formValue.value.facCode = val;
  formValue.value.systemCode = [];
  getSystem();
};

// 厂区组件调用父组件
const changeOutFactory = val => {
  queryParams.value.facCode = val;
};

/** 新增按钮操作 */
const handleAdd = () => {
  open.value = true;
};

/** 修改按钮操作 */
const handleEdit = row => {
  formValue.value = JSON.parse(JSON.stringify(row));
  open.value = true;
};

/** 提交按钮 */
const submitForm = () => {
  proxy.$refs["boardRef"].validate(valid => {
    if (valid) {
      const { systemCode, resourceId, resourcePaths } = formValue.value;
      const filterSystemCode = Array.isArray(systemCode) ? systemCode[systemCode?.length - 1] : systemCode ? systemCode : "";
      const filterResourceId = Array.isArray(resourceId) ? resourceId[resourceId?.length - 1] : resourceId;
      if (formValue.value.componentNumber) {
        editTableData({
          ...formValue.value,
          systemCode: filterSystemCode,
          resourceId: filterResourceId,
          resourcePaths: Array.isArray(resourceId) ? resourceId : resourcePaths
        }).then(() => {
          PxMessage.success("修改成功");
          queryTable();
          cancel();
        });
      } else {
        addTableData({ ...formValue.value, systemCode: filterSystemCode, resourceId: filterResourceId, resourcePath: resourceId }).then(() => {
          PxMessage.success("新增成功");
          queryTable();
          cancel();
        });
      }
    }
  });
};
/** 删除按钮操作 */
const handleDelete = row => {
  const { componentName, componentNumber } = row;
  PxMessageBox.confirm(`是否确认删除组件名称为${componentName}的数据项？`, "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      await delTableData({ componentNumber });
      PxMessage.success("删除成功");
      queryTable();
    })
    .catch(() => {});
};

/** 启用/禁用按钮操作 */
const handleDisabled = row => {
  const { componentName, componentNumber, isUse } = row;
  PxMessageBox.confirm(`是否确认${isUse === 1 ? "启用" : "禁用"}组件名称为${componentName}的数据项？`, "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      await disabledData({ componentNumber, isUse: isUse === 1 ? 0 : 1 });
      PxMessage.success(`${isUse === 1 ? "启用" : "禁用"}成功`);
      queryTable();
    })
    .catch(() => {});
};
</script>

<style lang="scss" scoped>
@import url("@/views/all/equip/scss/table-list.scss");

.flex-row {
  padding-top: 24px;
  display: flex;
  flex-direction: row;
  align-items: flex-start;
  justify-content: space-between;
}

.custom-form-ui .px-form-item:nth-child(2) {
  width: 400px;
}
</style>
